import { omit } from 'lodash-es'
import { KeepAlive } from '@vue/runtime-core'

/**
 * @ProjectName： naive-admin
 * @FileName： multi-tab-consumer
 * @Description: // 消费组建
 * @Author: ellwood
 * @date: 2024/2/20 - 8:16
 * @Version: V1.0.0
 */
export const MultiTabConsumer = defineComponent({
  name: 'MultiTabConsumer',
  setup(_props, { slots }) {
    // 类似<script setup lang="ts"></script>写法
    const state = useMultiTabInject()
    const route = useRoute()

    const getCurrentItem = () => {
      const path = route.path
      return state.tabList?.find(item => item.path === path)
    }

    return () => {
      // 类似<template>写法
      const component = slots.default?.()
      if (!component)
        return null

      let currentItem = getCurrentItem()

      const componentCache = toRaw(state.componentCache)

      if (!currentItem) {
        currentItem = {
          path: route.path,
          tabTitle: route.meta.title,
          route: omit(route, ['matched']),
          key: state.guid(),
        }
        state.tabList?.push(currentItem)
      }

      const exclude: string[] = []
      if (route.meta.keepAlive === false && isReactive(currentItem))
        exclude.push(currentItem.key!)

      // 缓存里面存在就使用缓存的，缓存不存在就创建一个新的
      const NewComp
                = componentCache[currentItem.key!]
                || defineComponent({
                  name: currentItem.key,
                  setup() {
                    return () => <>{component}</>
                  },
                })

      if (exclude.find(k => k === currentItem?.key))
        delete componentCache[currentItem.key!]
      else componentCache[currentItem.key!] = NewComp

      return (
        <KeepAlive exclude={exclude}>
          <NewComp key={currentItem.key + route.fullPath} />
        </KeepAlive>
      )
    }
  },
})
